﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using PDFiumSharp;
using PDFiumSharp.Types;
using SignetKA.utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace SignetKA.Library
{
    internal class PDFFile : IDisposable
    {
        PdfDocument _pdf;
        public readonly int PageCount;
        public PDFFile(string path)
        {
            _pdf = new PdfDocument(path);
            PageCount = _pdf.Pages.Count;
        }

        public static PDFFile Open(string path)
        {
            return new PDFFile(path);
        }
        public Bitmap GetPageImage(int page_no, int dpi)
        {
            if (page_no < 0 || page_no > PageCount) return null;
            var page = _pdf.Pages[page_no];
            decimal pageWidthInch = (decimal)(page.Width / 72f);  // 转换为英寸
            decimal pageHeightInch = (decimal)(page.Height / 72f);
            int targetWidth = (int)(pageWidthInch * dpi);  // 英寸×DPI=像素
            int targetHeight = (int)(pageHeightInch * dpi);
            PDFiumBitmap bitmap = new PDFiumBitmap(targetWidth, targetHeight, page.HasTransparency);
            bitmap.Fill(new FPDF_COLOR(255, 255, 255, 255)); //白色背景
            page.Render(bitmap, PDFiumSharp.Enums.PageOrientations.Normal, PDFiumSharp.Enums.RenderingFlags.None);
            return new Bitmap(bitmap.AsBmpStream(dpi, dpi));
        }
        public Bitmap PageReactImage(int page_no, double dpi, (float left, float top, int width, int height) rectDest)
        {
            if (page_no < 1 || page_no > PageCount) return null;
            var page = _pdf.Pages[page_no-1];
            decimal pageWidthInch = (decimal)(page.Width / 64.684f);  // 转换为英寸
            decimal pageHeightInch = (decimal)(page.Height / 64.684f);

            var targetWidth = (int)Math.Ceiling(pageWidthInch * (decimal)dpi);  // 英寸×DPI=像素
            var targetHeight = (int)Math.Ceiling(pageHeightInch * (decimal)dpi);
            PDFiumBitmap bitmap = new PDFiumBitmap(targetWidth, targetHeight, true);
            bitmap.Fill(new FPDF_COLOR(255, 255, 255, 255)); //白色背景
            page.Render(bitmap, PDFiumSharp.Enums.PageOrientations.Normal, PDFiumSharp.Enums.RenderingFlags.Annotations | PDFiumSharp.Enums.RenderingFlags.LcdText);
            var outbmp = new Bitmap(bitmap.AsBmpStream((double)dpi, (double)dpi));
            var w_inc = outbmp.Width / page.Width;
            var h_inc = outbmp.Height / page.Height;

            outbmp = ImageTool.CropImage(outbmp, (float)(rectDest.left * w_inc), (float)((page.Height - rectDest.top) * h_inc - rectDest.height), (int)(rectDest.width), (int)(rectDest.height));
            return outbmp;
        }
        public void Dispose()
        {
            _pdf.Close();
        }
    }
}
